::: scene subject

# GORM 框架篇

## 多条记录和查询条件

:::

::: scene code 查询多条记录

```go
users = []User{}
result := db.Find(&users)
```

L2->查询多条记录只需 Find 方法和数组类型的变量即可。

```sql
SELECT * FROM `users`
```

L1->这是最终构造出来的 SQL 语句。

:::

::: scene code 获取匹配到的第一条记录

```go
user := User{}
db.Where("name = ?", "jinzhu").First(&user)
```

```sql
SELECT * FROM users WHERE name = 'jinzhu' ORDER BY id LIMIT 1
```

:::

::: scene code 获取匹配到的所有记录

```go
users := []User{}
db.Where("name <> ?", "jinzhu").Find(&users)
```

```sql
SELECT * FROM users WHERE name <> 'jinzhu'
```

:::

::: scene code IN 语句查询

```go
users := []User{}
db.Where("name IN ?", []string{"jinzhu", "jinzhu 2"}).Find(&users)
```

```sql
SELECT * FROM users WHERE name IN ('jinzhu','jinzhu 2')
```

:::

::: scene code LIKE 语句查询

```go
db.Where("name LIKE ?", "%jin%").Find(&users)
```

```sql
SELECT * FROM users WHERE name LIKE '%jin%'
```

:::

::: scene code AND 语句查询

```go
db.Where("name = ? AND age >= ?", "jinzhu", "22").Find(&users)
```

```sql
SELECT * FROM users WHERE name = 'jinzhu' AND age >= 22
```

:::

::: scene code Time 时间查询

```go
db.Where("updated_at > ?", lastWeek).Find(&users)
```

```sql
SELECT * FROM users WHERE updated_at > '2000-01-01 00:00:00'
```

:::

::: scene code BETWEEN 区间查询

```go
db.Where("created_at BETWEEN ? AND ?", lastWeek, today).Find(&users)
```

```sql
SELECT * FROM users WHERE created_at BETWEEN '2000-01-01 00:00:00' AND '2000-01-08 00:00:00'
```

:::

::: scene link 更多资料 https://imshann.gitee.io/study-go/gorm/query.html

:::

::: scene 感谢观看

<p className="text-center text-4xl mt-32">如果你喜欢我创作的内容，邀请你关注、投币或收藏</p>
<p className="text-center text-4xl mt-24" style={{ color: "#ffde00" }}>Author：黑爷</p>

:::

